 
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;
import hc.trip.airticket.httpclient.JsonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**四川航空
 * @author 0707
 * @date 2011-3-6
 * @description TODO  : 
 */
public class GetFlightList3U {

	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			String line = "";   //查询条件组合
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "scal.com.cn");
		    header.put("Referer", "http://scal.com.cn/ScalB2CWeb/");
    
		    
		    postData.put("AdultNum", "1");
		    postData.put("ChildNum", "0");
		    postData.put("OrderType","0");
		    
		    line = queryInfo.getOrgCity()+"/"+queryInfo.getDesCity()+"/"+queryInfo.getDateString();
		    postData.put("line", line);
		    
		    postData.put("radioSingle", "0");
		    postData.put("select", "1");
		    postData.put("select", "0");
		    postData.put("select", "0");
		   // postData.put("endCity", "ZBAA"); 
		   // postData.put("startCity", "ZUUU");
		     
	        try {
	        	//返回的HTML
				responseText = proxy.doRequest(
		 	    "http://scal.com.cn/ScalB2CWeb/ETicket/AirlineList.aspx", postData, header,"UTF-8");
				 
				 //System.out.println(responseText);
				 resultInfo = (ResultInfo)analyzeResopnseText(responseText);
	  
			}catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
	        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
	
	          	return resultInfo;
			 
		}
		
		
		/**
		 * 根据山东航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象

		      if (source==null||source.trim().length()==0) {
				return null;
			}
	 		  String[] parts = source.split("<tr class=\"list\" id=\"Ctrl_tr.*?\">"); //将每一个航班区分开来
			  //System.out.println(source);
	 		  if (parts.length==0) {     //没有航班信息
				System.out.println("四川航空没有该线路的航班信息");
				return null;
			}
 
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			     regexSB.append("<td align=\"center\">(.*?)</td>\\s*<td align=\"center\">(.*?)</td>\\s*<td align=\"center\">(.*?)</td>\\s*"); 
			     regexSB.append("<td align=\"center\">(.*?)</td>\\s*<td align=\"center\">.*?</td>");
	 

			     //航班号  ，航班号+代码共享 ，出发时间，降落时间。
			     String regex =regexSB.toString();
			      

			  
			     
			     //<input value="3U8881~CTU-PEK~320~2011-3-31 7:20:00~2011-3-31 9:40:00~50~90~0~50~1440~2160~F~6~2160~2740~未办理值机免费退票,办理值机后收票面价5%退票手续费,免费改期,允许签转~F--~489-28367-44-F,FF~免费退票,免费改期,可升舱至Y舱与F舱,免费签转~YCH--~464-0-0-YCH--~720~免费退票,免费改期,可升舱至Y舱与F舱,免费签转~FCH--~464-0-0-FCH--~1080$ikHClWcQfhAZF3N5gn6oYJIhC7jbSDi1dKc7LX38jQso9T3ak6O8Q3GVLN4vBieagTo8s6MbYIbbj9zyC8r8jo4rA8bZiPnjrJjKyO5M7JB1scG4+rOnU/UtGMWrymGEIo4ihVwBBnJl16MeRytvbQQG/TbdDxc+LmlU5YPEYnQ=" name="ctl00$HomeMasterContentPlaceHolder$repeaterReturn$ctl00$repeaterItem$ctl01$repeaterCabin$ctl01$OrderData" type="radio" id="ctl00_HomeMasterContentPlaceHolder_repeaterReturn_ctl00_repeaterItem_ctl01_repeaterCabin_ctl01_OrderData" class="CTU-PEK" />
                  
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
		 

			     FlightInfo tempInfo = null;
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
			     //依次取出每个航班的信息,因为parts[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
 				 StringBuffer priceRegexSB = new StringBuffer();
			     Matcher matcher = p.matcher(parts[j]);
			     if(matcher.find())   //匹配航班信息
			     {	    	 
 
			    	 String flightNo = matcher.group(1).trim();
			    	// String flightNoAndShareCode = matcher.group(2).trim();
			    	 tempInfo.setFlightNo(flightNo);  //航班号
			    	//判断是否是代码共享
			  
			    	 //判断代码共享结束
			    	 tempInfo.setTakeOffTime(matcher.group(2).trim());
			    	 tempInfo.setArriveTime(matcher.group(3).trim());
			    	 tempInfo.setPlaneType(matcher.group(4).trim());
			     }
			     
			     priceRegexSB.append("<input value=\""+tempInfo.getFlightNo());
			     priceRegexSB.append("~.*?~"+tempInfo.getPlaneType()+"~.*?~.*?~.*?~.*?~.*?~.*?~.*?~.*?~(.*?)~.*?~(.*?)~(.*?)~(.*?)~.*?/>");
			     Pattern pPrice = Pattern.compile(priceRegexSB.toString(),Pattern.CASE_INSENSITIVE);
			    //  System.out.println(priceRegexSB.toString()+"\n");
               //<input value="3U8881~CTU-PEK~320~2011-3-31 7:20:00~2011-3-31 9:40:00~50~90~0~50~1440~2160~F~6~2160~2740~未办理值机免费退票,办理值机后收票面价5%退票手续费,免费改期,允许签转~F--~489-28367-44-F,FF~免费退票,免费改期,可升舱至Y舱与F舱,免费签转~YCH--~464-0-0-YCH--~720~免费退票,免费改期,可升舱至Y舱与F舱,免费签转~FCH--~464-0-0-FCH--~1080$ikHClWcQfhAZF3N5gn6oYJIhC7jbSDi1dKc7LX38jQso9T3ak6O8Q3GVLN4vBieagTo8s6MbYIbbj9zyC8r8jo4rA8bZiPnjrJjKyO5M7JB1scG4+rOnU/UtGMWrymGEIo4ihVwBBnJl16MeRytvbQQG/TbdDxc+LmlU5YPEYnQ=" name="ctl00$HomeMasterContentPlaceHolder$repeaterReturn$ctl00$repeaterItem$ctl01$repeaterCabin$ctl01$OrderData" type="radio" id="ctl00_HomeMasterContentPlaceHolder_repeaterReturn_ctl00_repeaterItem_ctl01_repeaterCabin_ctl01_OrderData" class="CTU-PEK" /> 	 
			      //<input value="3U8889~.*?~321~.*?~.*?~.*?~.*?~.*?~.*?~.*?~.*?~(.*?)~.*?~(.*?)~(.*?)~(.*?)

			      //分析价格start
			    	 Matcher mPrice = pPrice.matcher(parts[j]);
			    	 double tempMinPrice = 0.0;
			    	 double tempMaxPrice = 0.0;
			    	 boolean isFirst = true;
			    	 while(mPrice.find()){
			    	  String tempString  =  mPrice.group(1).trim();
			    	  if (tempString==null||tempString.trim().length()<=0) {
						return null ;     //没有匹配到舱位
					}
			    	  priceInfo = new PriceInfo();
			    	  priceInfo.setSpace(tempString);    //舱位
			    	
			    	  String pricetempString  = mPrice.group(3).trim();
			    	 if (pricetempString==null||pricetempString.trim().length()<=0) {
			    		 System.out.println("四川航空没有匹配到价格");
			    		 // return null; 	
					}
			    	 priceInfo.setPrice(Double.parseDouble(pricetempString));  //价格
			    	
			    	  String remindtempString = mPrice.group(4).trim();
			    		 if (remindtempString==null||remindtempString.trim().length()<=0) {
				    		 System.out.println("四川航空没有匹配到退改签需知");
				    		 // return null; 	
						}
			         priceInfo.setRemind(remindtempString);    //退改签需知
 
				      priceList.add(priceInfo);
				    	  
				    	  //一个航班不同cabin的最低和最高价格获取
				    	  if (isFirst) {
				    		  tempMinPrice = priceInfo.getPrice();
				    		  tempMaxPrice = priceInfo.getPrice();
				    		  tempInfo.setMinprice(tempMinPrice);
				    		  tempInfo.setMaxprice(tempMaxPrice);
				    		  isFirst = false;
						}
				    	 
						     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
						    	 tempMinPrice = priceInfo.getPrice();
								}
						     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
						    	 tempMaxPrice = priceInfo.getPrice(); 
							}
						     tempInfo.setMaxprice(tempMaxPrice);
						     tempInfo.setMinprice(tempMinPrice);
			    	 }
			     tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			     
			     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
			     
 		     	 }
 		    resultInfo.setResultList(flightInfos);	  
 		 	 
			return resultInfo;
		}




}
